package com.dhq.controller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.dhq.utils.PoolCache;
import com.dhq.utils.ScanPool;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "qr")
public class QRController {

    /**
     * 生成二维码方法
     *
     * @param content 要生成的内容
     * @param resp    response对象
     * @throws Exception 抛出异常
     */
    @RequestMapping(value = "/qrcode")
    public void getQrcode(String content, HttpServletResponse resp) throws Exception {
        ServletOutputStream stream = null;
       /* Long qrid=Long.parseLong(content);
        Ticket ticket=ticketRepository.findByTicketId(qrid);
       if (ticket!=null) {*/
        try {
            stream = resp.getOutputStream();
            Map<EncodeHintType, Object> hints = new HashMap<>();
            //编码
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            //边框距
            hints.put(EncodeHintType.MARGIN, 0);
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bm = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, 200, 200, hints);
            MatrixToImageWriter.writeToStream(bm, "png", stream);
        } catch (WriterException e) {
            e.getStackTrace();

        } finally {
            if (stream != null) {
                stream.flush();
                stream.close();
            }
        }
    }

    //生成二维码
    @RequestMapping("/qrcode/{uuid}")
    public String createQRCode(@PathVariable String uuid, HttpServletResponse response) {
        System.out.println("生成二维码");
//        String text = "http://localhost:11000/qr/login/" + uuid;
        String text = "http://www.baidu.com";
        int width = 300;
        int height = 300;
        String format = "png";
        //将UUID放入缓存
        ScanPool pool = new ScanPool();
        PoolCache.cacheMap.put(uuid, pool);
        try {
            Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//hints.put(EncodeHintType.MARGIN, 1);
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); //容错率
            BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
            MatrixToImageWriter.writeToStream(bitMatrix, format, response.getOutputStream());
        } catch (WriterException e) {
// TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
// TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    //查询是否被扫
    @RequestMapping("/pool")
    public String pool(String uuid) {
        System.out.println("检测[" + uuid + "]是否登录");

        ScanPool pool = PoolCache.cacheMap.get(uuid);

        if (pool == null) {
            return "timeout";
        }

//使用计时器，固定时间后不再等待扫描结果--防止页面访问超时
        new Thread(new ScanCounter(uuid)).start();

        boolean scanFlag = pool.getScanStatus();
        if (scanFlag) {
            return "success";
        } else {
            return "fail";
        }
    }

    //被扫后
    @RequestMapping("/login/{uuid}")
    public String login(@PathVariable String uuid) {

        ScanPool pool = PoolCache.cacheMap.get(uuid);

        if (pool == null) {
            return "timeout,scan fail";
        }

        pool.scanSuccess();

        return "scan success";
    }

    class ScanCounter implements Runnable{

        public Long timeout = 27000L;

        //传入的对象
        private String uuid;

        public ScanCounter(String p){
            uuid = p;
        }

        @Override
        public void run()
        {
            // TODO Auto-generated method stub
            try
            {
                Thread.sleep(timeout);
            } catch (InterruptedException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            notifyPool(uuid);
        }

        public synchronized void notifyPool(String uuid){
            ScanPool pool = PoolCache.cacheMap.get(uuid);
            pool.notifyPool();
        }

    }
}
